// Learn TypeScript:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/life-cycle-callbacks.html

import GameEvent from "../../Commons/GameEvent";
import RankManager, { RankEvent } from "../../Models/Ranks/RankManager";
import BaseUI from "../BaseUI";
import RankItem from "../UIItems/RankItem";

const { ccclass, property } = cc._decorator;

@ccclass
export default class RankUI extends BaseUI {

    @property(cc.ScrollView)
    scrollview: cc.ScrollView = null;

    rankItems: RankItem[];

    protected onLoad(): void {
        this.rankItems = [];

        var arr: cc.Node[] = this.scrollview.content.children;

        for (let i = 0; i < arr.length; i++) {
            var scriptItem = arr[i].getComponent(RankItem);
            this.rankItems.push(scriptItem);
            arr[i].active = false;
        }
    }


    protected onEnable(): void {
        RankManager.single.onUploadRank();

        GameEvent.eventNode.on(RankEvent.UPDATARANK_EVENT, this.onUpdataRank, this);
    }

    protected onDisable(): void {
        GameEvent.eventNode.off(RankEvent.UPDATARANK_EVENT, this.onUpdataRank, this);
    }

    drawView() {
        var rankArr: any[] = RankManager.single.rankList;
        for (let i = 0; i < this.rankItems.length; i++) {
            const element = this.rankItems[i];
            if (i < rankArr.length) {
                element.node.active = true;
                element.drawItem(rankArr[i]);
            } else {
                element.node.active = false;
            }
        }
    }
    onUpdataRank() {
        this.drawView();
    }
}
